import Vue from 'vue'
import Vuex from 'vuex';

// 必须在使用vuex前调用该插件
Vue.use(Vuex);

// const imgLoader = require.context("../assets", true, /^.\/jk/);
const actions = {
    autoChange() {
        state.timer = setInterval(mutations.AutoChange, 2500)
    },
    loadImages(context) {
        const lockList = [];
        state.isImgLockedList.forEach((s, i) => s && lockList.push(state.imgList[i]));
        const url = context.state.serverUrl + (context.getters.isLogin ? '/user' : '/api') + '/getPics';
        const config = {
            params: {
                lockList,
                imgSource: context.state.imgSource,
                imgNum: context.state.nextImageNum,
                friendList: context.state.friendList,
            }
        };
        if (context.getters.isLogin) {
            config['headers'] = {Authorization: localStorage.getItem('token')};
        }
        const vm = this._vm;
        vm.$axios.get(url, config).then(res => {
                if (res.data['status'] === 0) {
                    context.commit('LoadImages', res.data['msg'])
                } else {
                    // alert(res.data['msg'])
                    vm.$alert(res.data['msg'], '加载图片错误')
                }
            }
        ).catch(err => {
            vm.$alert(err.message, '网络连接出错')
        })
    },
    async checkToken(context) {
        const token = localStorage.getItem('token');
        if (token) {
            context.state.token = token;
            const vm = this._vm;
            try {
                const res = await vm.$axios.get(context.state.serverUrl+'/user/autoLogin', {
                    headers: {Authorization: token},
                });
                if (res.data['status'] === 0) {
                    const {username, friends, messages} = res.data['msg'];
                    context.state.username = username;
                    if (friends) context.state.friendList = friends.split(';');
                    if (messages) context.state.messages = JSON.parse(messages);
                    vm.$message.success('欢迎回来！ ' + context.state.username)
                } else {
                    vm.$message.error(res.data['msg'])
                    if (res.data['status'] === 2) {
                        // 去除无效token
                        localStorage.removeItem('token');
                    }
                }
            } catch(err) {
                vm.$alert(err.message, '网络连接出错')
            }
        }
        await context.dispatch('loadImages');
    },
};
const mutations = {
    SwitchLight(state) {
        state.lightState = !state.lightState;
    },
    AutoChange() {
        if (state.currentIndex < state.imageNum-1) state.currentIndex++;
        else state.currentIndex = 0;
    },
    CircleChange(state, target) {
        state.currentIndex = target;
        if (state.isAutoSwitch) {
            clearInterval(state.timer);
            actions.autoChange();
        }
    },
    LoadSettings(state) {
        let val;
        val = state.username !== '' ? localStorage.getItem('imgSrc') : 'public';
        state.imgSource = val || 'public';
        val = localStorage.getItem('imgNum');
        state.imageNum = val ? parseInt(val, 10) : 10;
        state.nextImageNum = state.imageNum;
        val = localStorage.getItem('isAuto');
        state.isAutoSwitch = val === null || val === 'true';
    },
    LoadImages(state, {urlList, sizeList}) {
        state.imageNum = urlList.length;
        state.isImgLockedList = new Array(urlList.length).fill(false);
        urlList.forEach((url, i) => Vue.set(state.imgList, i, url));
        // urlList.forEach(url => state.imgList.push(url));
        sizeList.forEach((size, i) => {
            const width = Math.max(150, Math.min(200, size.width / 5));
            Vue.set(state.imgSizes, i, [width, size.height * width / size.width])
        })
        // state.imgSizes = new Array(state.imageNum).fill(["100%", "100%"]);
        // state.imageNum = imgLoader.keys().length;
        // imgLoader.keys().forEach(url => state.imgList.push(imgLoader(url)));
    },
    // InitImageSize(state, images) {
    //     for (let i in images) {
    //         const image = images[i][0];
    //         // state.imgSizes[i] = [image.naturalWidth, image.naturalHeight];
    //         image.width = Math.max(150, Math.min(200, image.naturalWidth / 5));
    //         state.imgSizes[i] = [image.width, image.naturalHeight * image.width / image.naturalWidth]
    //     }
    // },

    StartWatching(state, e) {
        if (Number(e.target.dataset.index) !== state.currentIndex) return
        state.isWatching = 'block';
        clearInterval(state.timer);
    },
    StopWatching(state, e) {
        if (Number(e.target.dataset.index) !== state.currentIndex) return
        state.isWatching = 'none';
        actions.autoChange();
    },
    ViewFollow(state, e) {
        if (Number(e.target.dataset.index) !== state.currentIndex) return
        // 鼠标在缩略图中的坐标
        const x = e.pageX - e.target.offsetLeft;
        const y = e.pageY - e.target.offsetTop;
        // 鼠标映射到大图中的相对坐标
        const X = x * 7.5;
        const Y = y * 7.5;
        const squeezedSize = state.imgSizes[state.currentIndex];
        // 大图尺寸
        const width = squeezedSize[0] * 7.5;
        const height = squeezedSize[1] * 7.5;
        // 视图框为圆形，半径为原图中较小边长
        // const shorterLength = Math.min(width, height) / 1.5;
        // const screenLength = Math.min(shorterLength, 800);
        const screenLength = 800;
        // 使视图中的大图左上角不会为空
        let moveX = Math.min(screenLength / 2 - X, 0);
        let moveY = Math.min(screenLength / 2 - Y, 0);
        // 使视图中的大图右下角不会为空
        moveX = Math.max(moveX, screenLength -width);
        moveY = Math.max(moveY, screenLength -height);
        state.moveX = moveX + 'px';
        state.moveY= moveY + 'px';
    },
    updateToken(state) {
        state.token = localStorage.getItem('token');
    }
};
const state = {
    lightState: true,
    currentIndex: 1,
    imageNum: 10,
    timer: -1,
    imgList: [],
    imgSizes: [],
    isWatching: "none",
    moveX: 0,
    moveY: 0,
    isSwitching: false,
    isImgLockedList: [],
    isFormDialogVis: false,
    serverUrl: 'http://192.168.88.1:8001',
    username: '',
    token: '',
    friendList: [],
    imgSource: 'public',
    nextImageNum: 1,
    isAutoSwitch: true,
    messages: {},
};

const getters = {
    tipTheme(state) {
        return state.lightState ? "dark" : "light";
    },
    isLogin(state) {
        return state.username !== ''
    },
    hasUnsolvedMsg(state) {
        for (const user in state.messages) {
            if (Object.keys(state.messages[user]).length > 0) return true
        }
        return false
    }
}

export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters,
})